var log4js = require('log4js')

var logConfig = require('../../config/log')

// 加载配置文件
log4js.configure(logConfig)

var logUtil = {}
var textC = {
  br: '\n',
  baseXin: '***************'
}
var errorLogger = log4js.getLogger('errorLogger')
var resLogger = log4js.getLogger('resLogger')

// 封装错误日志
logUtil.logError = function (ctx, error, resTime) {
  if (ctx && error) {
    errorLogger.error(formatError(ctx, error, resTime))
  }
}

// 封装响应日志
logUtil.logResponse = function (ctx, resTime) {
  if (ctx) {
    resLogger.info(formatRes(ctx, resTime))
  }
}

// 格式化响应日志
var formatRes = (ctx, resTime) => {
  let logText = ''
  // 响应日志开始
  logText += `${textC.br}${textC.baseXin} Response log start ${textC.baseXin}${textC.br}`
  // 添加请求日志
  logText += formatReqLog(ctx.request, resTime)
  // 响应状态码
  logText += `Response status: ${ctx.status}${textC.br}`
  // 响应内容
  logText += `Response body: ${textC.br}${JSON.stringify(ctx.body)}${textC.br}`
  // 响应日志结束
  logText += `${textC.baseXin} Response log end ${textC.baseXin}${textC.br}`
  return logText
}

// 格式化错误日志
var formatError = (ctx, err, resTime) => {
  var logText = ''
  // 错误信息开始
  logText += `${textC.br}${textC.baseXin} Error log start ${textC.baseXin}${textC.br}`
  // 添加请求日志
  logText += formatReqLog(ctx.request, resTime)
  // 错误名称
  logText += `err name: ${err.name}${textC.br}`
  // 错误信息
  logText += `err message: ${err.message}${textC.br}`
  // 错误详情
  logText += `err stack: ${err.stack}${textC.br}`
  // 错误信息结束
  logText += `${textC.baseXin} Error log start ${textC.baseXin}${textC.br}`

  return logText
}

// 格式化请求日志
var formatReqLog = (req, resTime) => {
  var logText = ''
  var method = req.method
  // 访问方法
  logText += `request method: ${method}${textC.br}`
  // 请求原始地址
  logText += `request originalUrl: ${req.originalUrl}${textC.br}`
  // 客户端ip
  logText += `request client ip: ${req.ip}${textC.br}`
  // 请求参数
  if (method === 'GET') {
    logText += `request query: ${JSON.stringify(req.query)}${textC.br}`
  } else {
    logText += `request body: ${textC.br}${JSON.stringify(req.body)}${textC.br}`
  }
  // 服务器响应时间
  logText += `response time: ${resTime}${textC.br}`
  return logText
}

export default logUtil
